package com.yangsir.mysite.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yangsir.mysite.common.R;
import com.yangsir.mysite.mapper.UserMapper;
import com.yangsir.mysite.pojo.User;
import com.yangsir.mysite.service.UserService;
import com.yangsir.mysite.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.regex.Pattern;

/**
* @author yf
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-06-22 16:55:16
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 用户登录
     * @param useraccount
     * @param password
     * @return
     */
    @Override
    public R<User> login(HttpServletRequest httpServletRequest, String useraccount, String password) {
//        检验是否为用户名登录
        String usernameRegex = "^[a-zA-Z0-9]{6,16}$";
        Pattern usernamepattern = Pattern.compile(usernameRegex);
        String mdpassword = DigestUtils.md5DigestAsHex(password.getBytes());
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (usernamepattern.matcher(useraccount).matches()) {
            queryWrapper.eq(User::getUserAccount,useraccount);
            return this.result(httpServletRequest, queryWrapper, mdpassword);
        }
//        检验是否为手机号登录
        String phoneRegex = "^1[3-9]\\d{9}$";
        Pattern phonePattern = Pattern.compile(phoneRegex);
        if (phonePattern.matcher(useraccount).matches()) {
            queryWrapper.eq(User::getPhone,useraccount);
            return this.result(httpServletRequest, queryWrapper, mdpassword);
        }
        return R.error("登录失败");
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public R<String> register(User user) {
        // 查询是否存在该用户名
        LambdaQueryWrapper<User> useraccountQueryWrapper = new LambdaQueryWrapper<>();
        useraccountQueryWrapper.eq(User::getUserAccount,user.getUserAccount()).eq(User::getIsDelete,0);

        if (userMapper.selectOne(useraccountQueryWrapper) != null) {
            return R.error("用户名已存在");
        }
        // 查询是否存在该手机号
        LambdaQueryWrapper<User> phonequeryWrapper = new LambdaQueryWrapper<>();
        phonequeryWrapper.eq(User::getPhone,user.getPhone()).eq(User::getIsDelete,0);
        if (userMapper.selectOne(phonequeryWrapper) != null) {
            return R.error("手机号已存在");
        }
        user.setUserPassword(DigestUtils.md5DigestAsHex(user.getUserPassword().getBytes()));
        userMapper.insert(user);

        redisUtils.removeSet(user.getPhone());
        return R.success("注册成功");
    }

    /**
     * 更新用户自己的信息
     * @param user
     * @return
     */
    @Override
    public R<User> upadteUser(HttpServletRequest httpServletRequest, User user) {
        User user1 = (User)httpServletRequest.getSession().getAttribute("user");
        if (user1 == null) {
            return R.error("请重新登陆");
        }
        if (!user1.getId().equals(user.getId())) {
            if (user1.getUserRole() != 2) {
                return R.error("权限不足");
            } else {
                userMapper.updateById(user);
                return R.success(userMapper.selectById(user.getId()),"更新成功");
            }
        }
        userMapper.updateById(user);
        return R.success(user,"更新成功");
    }

    /**
     * 获取所有用户 (管理员)
     * @param
     * @return
     */
    @Override
    public R<List<User>> getAllUser() {
        List<User> users = userMapper.selectList(null);
        users.forEach(user -> {
            user.setUserPassword(null);
        });
        return R.success(users,"用户已全部获取");
    }

    /**
     * 创建用户 (管理员)
     * @param user
     * @return
     */
    @Override
    public R<String> createUser(User user) {
        user.setUserPassword(DigestUtils.md5DigestAsHex(user.getUserPassword().getBytes()));
        if (userMapper.insert(user) != 1) {
            return R.error("创建失败");
        }
        return R.success("创建成功");
    }

    /**
     * 搜索用户信息 (管理员)
     * @param str
     * @return
     */
    @Override
    public R<List<User>> selectUserByStr(String str) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (str == "禁用") {
            queryWrapper.eq(User::getUserStatus,1);
        } else if (str == "正常") {
            queryWrapper.eq(User::getUserStatus,0);
        } else {
            queryWrapper.like(User::getUsername,str);
            queryWrapper.or().like(User::getUserAccount,str);
            queryWrapper.or().like(User::getPhone,str);
            queryWrapper.or().like(User::getEmail,str);
            queryWrapper.or().like(User::getCreateTime,str);
        }
        List<User> users = userMapper.selectList(queryWrapper);
        return R.success(users, "搜索成功");
    }

    /**
     * 根据Role查询用户 (管理员)
     * @param role
     * @return
     */
    public R<List<User>> getUserByRole(Integer role) {
        // 检查用户权限
        if (role == 3) {
            List<User> users = userMapper.selectList(null);
            return R.success(users,"查询成功");
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserRole,role);
        List<User> users = userMapper.selectList(queryWrapper);
        return R.success(users,"查询成功");
    }

    /**
     * 删除用户 (管理员)
     * @param id
     * @return
     */
    @Override
    public R<String> deleteUserById(Long id) {
        if (userMapper.deleteById(id) == 1) {
            return R.success("已删除");
        }
        return R.error("删除失败");
    }

    /**
     * 禁用或启动用户 (管理员)
     * @param
     * @param user
     * @return
     */
    @Override
    public R<String> deactivateUser(User user) {
        if (userMapper.updateById(user) != 1) {
            return user.getUserStatus() == 1 ? R.success("禁用失败") : R.success("解封失败");
        }
        return user.getUserStatus() == 1 ? R.success("禁用成功") : R.success("解封成功");
    }

    // 登录用户状态检测
    private R<User> result(HttpServletRequest httpServletRequest, LambdaQueryWrapper<User> queryWrapper, String mdpassword){
        User one = userMapper.selectOne(queryWrapper);
        if (one == null) {
            return R.error("用户名不存在");
        } else if (one.getIsDelete() == 1) {
            return R.error("用户已被删除");
        } else if (one.getUserStatus() == 1) {
            return R.error("用户已被禁用");
        } else if (!one.getUserPassword().equals(mdpassword)) {
            return R.error("密码错误");
        }
        // 数据脱敏
        one.setUserPassword(null);
        httpServletRequest.getSession().setAttribute("user", one);
        return R.success(one,"登录成功");
    }
}




